import { useRef, useEffect, useContext, useCallback } from "react";
import { useDidShow } from "@tarojs/taro";
import { TopContext } from "./useTopView";
var useOverlay = function (componentName /** 便于调试LOG */) {
    var _a = useContext(TopContext), popup = _a.popup, close = _a.close, forcedClose = _a.forcedClose, topView = _a.topView;
    var isShowRef = useRef(false);
    var needShow = useRef(false);
    var componentRef = useRef();
    var optionsRef = useRef();
    var resolveRef = useRef();
    var rejectRef = useRef();
    var componentIdRef = useRef(0); // 当前show出组件唯一标识
    useDidShow(function () {
        isShowRef.current = true;
        if (needShow.current) {
            needShow.current = false;
            if (componentRef.current) {
                _show(componentRef.current, optionsRef.current)
                    .then(function (res) {
                    resolveRef.current && resolveRef.current(res);
                })
                    .catch(function (e) {
                    rejectRef.current && rejectRef.current(e);
                });
            }
        }
    });
    useEffect(function () {
        return function () {
            componentIdRef.current && close(componentIdRef.current);
        };
    }, [componentIdRef, componentName]);
    var _show = useCallback(function (component, options) {
        if (options === void 0) { options = {}; }
        var id = new Date().getTime();
        componentIdRef.current = id;
        return popup({ id: id, component: component }, options);
    }, [componentIdRef, componentName, popup]);
    // needVerifyShow: 是否需要验证组件是否didshow。应当在所有组didshow才能show，但出于部分场景[authbutton]组件显示了，但未走usedidshow，前期先不加判断，只在指定场景加，后期再解决未何部分场景组件显示了却未走usedidshow
    var show = useCallback(function (component, options, needVerifyShow) {
        if (options === void 0) { options = {}; }
        if (needVerifyShow === void 0) { needVerifyShow = false; }
        // 当前组件未显示，则等待下次显示时主动显示
        if (needVerifyShow && !isShowRef.current) {
            needShow.current = true;
            componentRef.current = component;
            optionsRef.current = options;
            return new Promise(function (resolve, reject) {
                resolveRef.current = resolve;
                rejectRef.current = reject;
            });
        }
        return _show(component, options);
    }, [_show]);
    var _close = useCallback(function () {
        componentIdRef.current && close(componentIdRef.current);
    }, [componentIdRef, componentName, close]);
    return { show: show, close: _close, forcedClose: forcedClose, overlayView: topView };
};
export default useOverlay;
